<?php
/**
 * 4位图片验证码类
 * tcc1988@163.com
 */
class CaptchaUtil{
	
	public $fontcolors = array(
			array(27,78,181), // blue
			array(22,163,35), // green
			array(214,36,7),  // red
			array(253,88,211),  // red
			array(11,11,11),  // red
	);
	public $fonts = array(
			 '/fonts/AHGBold.ttf'
	);
	public $width = 100;
	public $height = 32;
	
	
	public $words = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
	
	public $captcha = '';
	
	public $im;
	
	public function __construct() {
		$this->fonts[0] = dirname(__FILE__).$this->fonts[0];
		
		$this->im = imagecreatetruecolor(100, 32);
		$gdBgColor = imagecolorallocate($this->im, 255,255,255);
		imagefilledrectangle($this->im, 0, 0, 100, 32,$gdBgColor);
		 
		$borderColor = imagecolorallocate($this->im,206,206,206);
		imagefilter($this->im, IMG_FILTER_GAUSSIAN_BLUR);
		
		$char1 = substr($this->words,rand(0, strlen($this->words)-1),1);
		$char2 = substr($this->words,rand(0, strlen($this->words)-1),1);
		$char3 = substr($this->words,rand(0, strlen($this->words)-1),1);
		$char4 = substr($this->words,rand(0, strlen($this->words)-1),1);
		$this->captcha = $char1.$char2.$char3.$char4;
		
		$fontcolor1 = $this->fontcolors[rand(0,count($this->fontcolors)-1)];
		$fontcolor1 = imagecolorallocate($this->im, $fontcolor1[0], $fontcolor1[1], $fontcolor1[2]);
		$fontcolor2 = $this->fontcolors[rand(0,count($this->fontcolors)-1)];
		$fontcolor2 = imagecolorallocate($this->im, $fontcolor2[0], $fontcolor2[1], $fontcolor2[2]);
		$fontcolor3 = $this->fontcolors[rand(0,count($this->fontcolors)-1)];
		$fontcolor3 = imagecolorallocate($this->im, $fontcolor3[0], $fontcolor3[1], $fontcolor3[2]);
		$fontcolor4 = $this->fontcolors[rand(0,count($this->fontcolors)-1)];
		$fontcolor4 = imagecolorallocate($this->im, $fontcolor4[0], $fontcolor4[1], $fontcolor4[2]);
		 
		imagettftext($this->im, rand(14,18), rand(-8,8), 20 , 25 , $fontcolor1 , $this->fonts[rand(0,count($this->fonts)-1)],$char1);
		imagettftext($this->im, rand(14,18), rand(-8,8), 35 , 25 , $fontcolor2 , $this->fonts[rand(0,count($this->fonts)-1)],$char2);
		imagettftext($this->im, rand(14,18), rand(-8,8), 50 , 25 , $fontcolor3 , $this->fonts[rand(0,count($this->fonts)-1)],$char3);
		imagettftext($this->im, rand(14,18), rand(-8,8), 65 , 25 , $fontcolor4 , $this->fonts[rand(0,count($this->fonts)-1)],$char4);
		 
		imageline($this->im,0,0,100,0, $borderColor);
		imageline($this->im,0,0,0,32, $borderColor);
		 
		imageline($this->im,99,0,99,31, $borderColor);
		imageline($this->im,0,31,99,31, $borderColor);
		
		
	}
	
	public function getCaptcha(){
		return $this->captcha;
	}
	
	public function writeImage(){
		header ('Content-Type: image/png');
		imagepng($this->im);
		imagedestroy($this->im);
	}

}